package com.nettylearning.base.netty.io.buffer;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author vince
 * @date 2021/7/17 7:40
 * @description 6. 直接缓冲区
 * @Version 1.0
 */
public class DirectBuffer {
    public static void main(String[] args) throws Exception {
        // 从磁盘尚读取文件内容
        String infile = "D://test.txt";
        FileInputStream fin = new FileInputStream(infile);
        FileChannel fcin = fin.getChannel();

        // 把读取的内容写入一个新文件
        String outfile = "D://testcopy.txt";
        FileOutputStream fout = new FileOutputStream(outfile);
        FileChannel fcout = fout.getChannel();

        // 使用allocateDirect,而非 allocate
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        while (true) {
            buffer.clear();
            int r = fcin.read(buffer);
            if (-1 == r) {
                break;
            }
            buffer.flip();
            fcout.write(buffer);
        }
    }
}
